package com.ozner.cup.Device.WaterPurifier.RoWifi;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.ozner.WaterPurifier.RoWifi.WaterPurifier_RO_WIFI;
import com.ozner.cup.Base.BaseActivity;
import com.ozner.cup.Base.WebActivity;
import com.ozner.cup.Bean.Contacts;
import com.ozner.cup.Command.OznerPreference;
import com.ozner.cup.DBHelper.DBManager;
import com.ozner.cup.DBHelper.UserInfo;
import com.ozner.cup.R;
import com.ozner.cup.UIView.UIZGridView;
import com.ozner.cup.Utils.WeChatUrlUtil;
import com.ozner.device.OznerDeviceManager;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;

import static com.ozner.cup.R.id.tv_ro_filter;

public class ROWifiFilterStatusActivity extends BaseActivity implements AdapterView.OnItemClickListener {
    private static final String TAG = "ROWifiFilterStatusActiv";
    public static final String PARMS_FILTER_A = "parms_filter_a";
    public static final String PARMS_FILTER_B = "parms_filter_b";
    public static final String PARMS_FILTER_C = "parms_filter_c";


    @InjectView(R.id.title)
    TextView title;
    @InjectView(R.id.toolbar)
    Toolbar toolbar;
    @InjectView(R.id.tv_ro_fit)
    TextView tvRoFit;
    @InjectView(R.id.tv_ro_filterRest)
    TextView tvRoFilterRest;
    @InjectView(tv_ro_filter)
    TextView tvRoFilter;
    @InjectView(R.id.tv_rolxa)
    TextView tvRolxa;
    @InjectView(R.id.tv_rolxb)
    TextView tvRolxb;
    @InjectView(R.id.tv_rolxc)
    TextView tvRolxc;
    @InjectView(R.id.laly_ro)
    LinearLayout lalyRo;
    @InjectView(R.id.iv_health_know)
    ImageView ivHealthKnow;
    @InjectView(R.id.tv_health_know)
    TextView tvHealthKnow;
    @InjectView(R.id.tds_health_know_layout)
    LinearLayout tdsHealthKnowLayout;
    @InjectView(R.id.iv_health_buy)
    ImageView ivHealthBuy;
    @InjectView(R.id.tv_health_buy_msg)
    TextView tvHealthBuyMsg;
    @InjectView(R.id.tds_health_buy_layout)
    LinearLayout tdsHealthBuyLayout;
    @InjectView(R.id.ll_en_no)
    LinearLayout llEnNo;
    @InjectView(R.id.tv_scancode_btn)
    TextView tvScancodeBtn;
    @InjectView(R.id.llay_scanCode)
    LinearLayout llayScanCode;
    @InjectView(R.id.uiz_moreProject)
    UIZGridView uizMoreProject;
    @InjectView(R.id.uiz_onzeService)
    UIZGridView uizOnzeService;
    @InjectView(R.id.llay_moreService)
    LinearLayout llayMoreService;


    private ArrayList<HashMap<String, Object>> projectList, serviceList;
    //更多产品
    private int[] projectImgs;// = {R.drawable.filter_status_tap, R.drawable.filter_status_purifier, R.drawable.filter_status_cup};
    private String[] projectStr;// = {"浩泽智能水探头", "金色伊泉系列", "浩泽智能杯"};
    private SimpleAdapter projectAdapter, serviceAdapter;
    //浩泽服务
    private int[] serviceImgs;
    private String[] serviceUpStr;
    private String[] serviceDownStr;
    private String mac;
    private WaterPurifier_RO_WIFI roWaterPurifier;
    private int index = 0;
    private UserInfo userInfo;
    private int filterA, filterB, filterC;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rowifi_filter_status);
        ButterKnife.inject(this);

        initToolBar();
        initStaticData();
        uizMoreProject.setOnItemClickListener(this);
        String userid = OznerPreference.GetValue(this, OznerPreference.UserId, "");
        if (!userid.isEmpty()) {
            userInfo = DBManager.getInstance(this).getUserInfo(userid);
        }
        try {
            String mac = getIntent().getStringExtra(Contacts.PARMS_MAC);
            if (!mac.isEmpty()) {
                roWaterPurifier = (WaterPurifier_RO_WIFI) OznerDeviceManager.Instance().getDevice(mac);
                if (roWaterPurifier.Type().equals("Ozner RO") || roWaterPurifier.Type().equals("RO Comml")) {
                    filterA = getIntent().getIntExtra(PARMS_FILTER_A, 0);
                    filterB = getIntent().getIntExtra(PARMS_FILTER_B, 0);
                    filterC = getIntent().getIntExtra(PARMS_FILTER_C, 0);
                    loadFilterInfo();
                }
            } else {
                new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT)
                        .setMessage(R.string.device_address_err)
                        .setPositiveButton(R.string.ensure, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                ROWifiFilterStatusActivity.this.finish();
                            }
                        }).show();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                break;
        }
        return true;
    }

    /**
     * 初始化ToolBar
     */
    private void initToolBar() {
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        title.setText(R.string.current_filter_state);
        toolbar.setNavigationIcon(R.drawable.back);
    }

    private void loadFilterInfo() {
        if (filterA >= 0) {
            tvRolxa.setText(filterA + "%");
        } else {
            tvRolxa.setText(R.string.state_null);
        }

        if (filterB >= 0) {
            tvRolxb.setText(filterB + "%");
        } else {
            tvRolxb.setText(R.string.state_null);
        }

        if (filterC >= 0) {
            tvRolxc.setText(filterC + "%");
        } else {
            tvRolxc.setText(R.string.state_null);
        }

        //复位键显示控制
        if (filterA == 0 || filterB == 0 || filterC == 0) {
            tvRoFilterRest.setVisibility(View.VISIBLE);
        } else {
            tvRoFilterRest.setVisibility(View.GONE);
        }

        try {
            if ((filterA >= 0 && filterA < 30) || (filterB >= 0 && filterB < 30) || (filterC >= 0 && filterC < 30)) {
                tvRoFilter.setVisibility(View.GONE);
            } else {
                tvRoFilter.setVisibility(View.GONE);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    public Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    tvRoFilter.clearAnimation();
                    tvRoFilter.setAnimation(getLoad());
                    break;
                case 2:
                    tvRoFilter.clearAnimation();
                    tvRoFilter.setAnimation(getOut());
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private Animation getLoad() {
        return AnimationUtils.loadAnimation(ROWifiFilterStatusActivity.this,
                                            R.anim.push_in);
    }

    private Animation getOut() {
        return AnimationUtils.loadAnimation(ROWifiFilterStatusActivity.this,
                                            R.anim.push_out);
    }

    /**
     * 初始化更多产品和安心服务数据
     */
    private void initStaticData() {
//        filterProgress.setThumb(R.drawable.filter_status_thumb);
        projectImgs = new int[]{R.drawable.filter_status_tap, R.drawable.filter_status_purifier, R.drawable.filter_status_cup};
        projectStr = new String[]{getString(R.string.Filter_Project1), getString(R.string.Filter_Project2), getString(R.string.Filter_Project3)};

        serviceImgs = new int[]{R.drawable.filter_status_00, R.drawable.filter_status_01,
                R.drawable.filter_status_10, R.drawable.filter_status_11,
                R.drawable.filter_status_20, R.drawable.filter_status_21,
                R.drawable.filter_status_30, R.drawable.filter_status_31
        };
        serviceUpStr = new String[]{getString(R.string.Filter_Service_up_00), getString(R.string.Filter_Service_up_01),
                getString(R.string.Filter_Service_up_10), getString(R.string.Filter_Service_up_11),
                getString(R.string.Filter_Service_up_20), getString(R.string.Filter_Service_up_21),
                getString(R.string.Filter_Service_up_30), getString(R.string.Filter_Service_up_31)
        };
        serviceDownStr = new String[]{getString(R.string.Filter_Service_down_00), getString(R.string.Filter_Service_down_01),
                getString(R.string.Filter_Service_down_10), getString(R.string.Filter_Service_down_11),
                getString(R.string.Filter_Service_down_20), "",
                "", ""
        };
        projectList = new ArrayList<HashMap<String, Object>>();
        serviceList = new ArrayList<HashMap<String, Object>>();
        loadMoreProjectData();
        loadServiceData();
    }


    /**
     * 加载更多产品数据
     */
    private void loadMoreProjectData() {
        projectList.clear();
        for (int i = 0; i < projectImgs.length; i++) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("itemImg", projectImgs[i]);
            map.put("itemText", projectStr[i]);
            projectList.add(map);
        }
        projectAdapter = new SimpleAdapter(this, projectList, R.layout.more_product_item,
                                           new String[]{"itemImg", "itemText"}, new int[]{R.id.iv_more_product_img, R.id.tv_more_product_text});

        uizMoreProject.setAdapter(projectAdapter);
    }

    /**
     * 加载安心服务数据
     */
    private void loadServiceData() {
        serviceList.clear();
        for (int i = 0; i < serviceImgs.length; i++) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("itemImg", serviceImgs[i]);
            map.put("itemTextUp", serviceUpStr[i]);
            map.put("itemTextDown", serviceDownStr[i]);
            serviceList.add(map);
        }
        serviceAdapter = new SimpleAdapter(this, serviceList, R.layout.more_ozner_service_item,
                                           new String[]{"itemImg", "itemTextUp", "itemTextDown"},
                                           new int[]{R.id.iv_more_service_img, R.id.tv_more_service_up_text, R.id.tv_more_service_down_text});

        uizOnzeService.setAdapter(serviceAdapter);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            case 0:
                if (userInfo != null && userInfo.getMobile() != null && !userInfo.getMobile().isEmpty()) {
                    String tapUrl = WeChatUrlUtil.formatFilterTapUrl(userInfo.getMobile()
                            , OznerPreference.getUserToken(ROWifiFilterStatusActivity.this), "zh", "zh");
                    startWebActivity(tapUrl);
                } else {
                    showToastCenter(R.string.userinfo_miss);
                }
                break;
            case 1:
                if (userInfo != null && userInfo.getMobile() != null && !userInfo.getMobile().isEmpty()) {
                    String goldUrl = WeChatUrlUtil.formatFilterGoldSpringUrl(userInfo.getMobile()
                            , OznerPreference.getUserToken(ROWifiFilterStatusActivity.this), "zh", "zh");
                    startWebActivity(goldUrl);
                } else {
                    showToastCenter(R.string.userinfo_miss);
                }
                break;
            case 2:
                if (userInfo != null && userInfo.getMobile() != null && !userInfo.getMobile().isEmpty()) {
                    String cupUrl = WeChatUrlUtil.formatFilterCupUrl(userInfo.getMobile()
                            , OznerPreference.getUserToken(ROWifiFilterStatusActivity.this), "zh", "zh");
                    startWebActivity(cupUrl);
                } else {
                    showToastCenter(R.string.userinfo_miss);
                }
                break;
        }
    }

    /**
     * 点击更多产品，跳转到指定商城页面
     *
     * @param url
     */
    private void startWebActivity(String url) {
        Intent filterIntent = new Intent(ROWifiFilterStatusActivity.this, WebActivity.class);
        filterIntent.putExtra(Contacts.PARMS_URL, url);
        startActivity(filterIntent);
    }
}
